import React from 'react'
import { Icon } from 'antd';
import Pop from './Pop'
import moment from 'moment'
import './index.less'
const shallowequal = require('shallowequal');
export default class MonthPickerRange extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      isopen: false,
      popPositionLeft: true,
      propsRange: props.range,
      value: props.value || '',
      range: props.range || [moment(new Date()).format('YYYY'), moment(new Date()).format('YYYY')]
    }
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    if (!shallowequal(nextProps.range, prevState.propsrange)) {
      return {
        ...prevState,
        propsrange: nextProps.range,
        value: nextProps.value || '',
        range: nextProps.range || [moment(new Date()).format('YYYY'), moment(new Date()).format('YYYY')]
      }
    }
    return null
  }

  closePop = () => {
    this.setState({
      isopen: false
    })
  }
  handleOpen = async(event) => {
    event.persist();
    await this.setState({
      isopen: true,
      popPositionLeft: event.clientX< document.body.clientWidth/2
    });
  }
  setSelectedDate = (val) => {
    this.setState({
      range: [val, this.state.range[1]]
    }, () => {
      if (this.props.onDateChange) {
        this.props.onDateChange(this.state.range)
      }
    })
  }
  setSelectedDate2 = (val) => {
    this.setState({
      range: [this.state.range[0], val]
    }, () => {
      if (this.props.onDateChange) {
        this.props.onDateChange(this.state.range)
      }
    })
  }
  render() {
    const { popPositionLeft } = this.state;
    return (
      <span className="pickwrap"
        style={this.props.style}
      >
        <span className="inputSpan"
          onClick={this.handleOpen}
        >
          <span className="innerSpan">
            <Icon className="i-left"
              type="schedule"
            />
            <input readOnly
              value={this.state.range[0]}
            />
            <span>~</span>
            <input readOnly
              value={this.state.range[1]}
            />
            <Icon className="i-right"
              type="caret-down"
            />
          </span>
        </span>
        {
          (() => {
            if(this.state.isopen){
              return <Pop closePop={this.closePop.bind(this)}
                popPositionLeft={popPositionLeft}
                range={this.state.range}
                setSelectedDate={this.setSelectedDate.bind(this)}
                setSelectedDate2={this.setSelectedDate2.bind(this)}
                value={this.state.value}
              />
            }
          })()
        }
      </span>
    )
  }
}